package com.ai_daily.aitiantian.util;

import android.util.Log;

import java.util.ArrayList;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class StringProcessor {
    private static final String TAG = "StringProcessor";
    private int maxChar;
    private List<Integer> lengths;

    public StringProcessor(int maxChar) {
        this.maxChar = maxChar;
    }

    public List<String> processString(String str) {
        this.lengths = new ArrayList<>();
        Log.d(TAG, "Sum String Length = " + str.length());
        List<String> speakData = new ArrayList<>();
        StringBuffer stringBuffer = new StringBuffer();
        String[] result = splitAndKeepSeparators(str, "[,.，？。：、]");
        Log.d(TAG, "String[] Length = " + result.length);

        for (String s : result) {
            if (stringBuffer.length() == 0) {
                stringBuffer.append(s);
            } else {
                if ((stringBuffer.length() + s.length()) > maxChar) {
                    addTextToSpeakData(speakData, stringBuffer.toString());
                    stringBuffer = new StringBuffer();
                    stringBuffer.append(s);
                } else {
                    stringBuffer.append(s);
                }
            }
        }

        if (stringBuffer.length() > 0) {
            addTextToSpeakData(speakData, stringBuffer.toString());
            Log.d(TAG, "Last String Length = " + stringBuffer.length());
            Log.d(TAG, "speakData Length = " + speakData.size());
        }

        return speakData;
    }

    public List<Integer> getLengths() {
        return lengths;
    }

    public void setLengths(List<Integer> lengths) {
        this.lengths = lengths;
    }

    private void addTextToSpeakData(List<String> speakData, String text) {
        if (text.length() > maxChar) {
            String[] result = splitStringByLength(text, maxChar);
            for (String s : result) {
                speakData.add(s);
                lengths.add(s.length());
            }
        } else {
            speakData.add(text);
            lengths.add(text.length());
        }
    }

    public static String[] splitAndKeepSeparators(String input, String regex) {
        List<String> parts = new ArrayList<>();
        Pattern pattern = Pattern.compile("([^" + Pattern.quote(regex) + "]+|[" + Pattern.quote(regex) + "])");
        Matcher matcher = pattern.matcher(input);

        while (matcher.find()) {
            parts.add(matcher.group());
        }

        return parts.toArray(new String[0]);
    }

    public static String[] splitStringByLength(String s, int length) {
        int arrayLength = (int) Math.ceil(s.length() / (double) length);
        String[] result = new String[arrayLength];

        for (int i = 0, j = 0; i < s.length(); i += length) {
            result[j++] = (i + length <= s.length()) ? s.substring(i, i + length) : s.substring(i);
        }

        return result;
    }
}
